package com.molichuxing.gateway.bff.basic.services.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.molichuxing.framework.dto.Paged;
import com.molichuxing.framework.exception.BizException;
import com.molichuxing.framework.result.ResponseCodeEnum;
import com.molichuxing.framework.utils.ObjectCastUtil;
import com.molichuxing.framework.utils.ValidateUtil;
import com.molichuxing.gateway.bff.advert.entity.response.MessageVo;
import com.molichuxing.gateway.bff.advert.entity.response.RiskEmailVo;
import com.molichuxing.gateway.bff.basic.convertor.Convert;
import com.molichuxing.gateway.bff.basic.entity.request.modify.RiskEmailModifyVo;
import com.molichuxing.gateway.bff.basic.entity.response.InsuranceCompanyVo;
import com.molichuxing.gateway.bff.basic.entity.response.OwnershipDetailVo;
import com.molichuxing.gateway.bff.basic.entity.response.OwnershipVo;
import com.molichuxing.gateway.bff.basic.entity.response.RegionCityVo;
import com.molichuxing.gateway.bff.basic.entity.response.SubcompanyVo;
import com.molichuxing.gateway.bff.basic.services.BasicBffService;
import com.molichuxing.gateway.bff.car.entity.response.RegionSubcompanyVo;
import com.molichuxing.services.business.service.RegionBizService;
import com.molichuxing.services.business.service.SubCompanyBizService;
import com.molichuxing.services.infrastructure.dto.request.modify.RiskEmailModifyDto;
import com.molichuxing.services.infrastructure.dto.response.OwnershipDto;
import com.molichuxing.services.infrastructure.dto.response.RegionCityDto;
import com.molichuxing.services.infrastructure.dto.response.RegionInfoDto;
import com.molichuxing.services.infrastructure.dto.response.RiskEmailDto;
import com.molichuxing.services.infrastructure.dto.response.SubcompanyDto;
import com.molichuxing.services.infrastructure.service.DealerService;
import com.molichuxing.services.infrastructure.service.InsuranceCompanyService;
import com.molichuxing.services.infrastructure.service.OwnershipService;
import com.molichuxing.services.infrastructure.service.RegionService;
import com.molichuxing.services.infrastructure.service.RiskEmailService;
import com.molichuxing.services.infrastructure.service.StoreService;
import com.molichuxing.services.infrastructure.service.SubcompanyService;
import com.molichuxing.services.property.RiskEmailTypeEnum;
import com.molichuxing.services.property.RiskEmailTypeExplainEnum;

@Service("basicBffService")
public class BasicBffServiceImpl implements BasicBffService {
	private static final Logger logger = LoggerFactory.getLogger(BasicBffServiceImpl.class);

	@Resource
	private RegionBizService regionBizService;

	@Resource
	private SubcompanyService subcompanyService;


	@Resource
	private OwnershipService ownershipService;

	@Resource
	private RegionService regionService;

	@Resource
	private SubCompanyBizService subCompanyBizService;

	@Resource
	private InsuranceCompanyService insuranceCompanyService;

    @Resource
    private DealerService dealerService;

    @Resource
    private StoreService storeService;
    
    @Resource
    private RiskEmailService riskEmailService;

	@Override
	public List<InsuranceCompanyVo> getInsurance() {
		return Convert.toInsuranceCompanyVoList(insuranceCompanyService.getInsurance());
	}

	@Override
	public List<RegionCityVo> getAllCity(Map<String, Object> selectParams) {
        Integer level = ObjectCastUtil.castInteger(selectParams.get("level"));
        List<RegionCityVo> regionCityVoList =  new ArrayList<RegionCityVo>();

        List<Integer> regionIdList = getRegionIdList(selectParams);
        List<RegionCityDto> regionCityDtoList  =  regionService.getAllCityByRegionId(level,regionIdList);
		if(null == regionCityDtoList || regionCityDtoList.size()<=0){
			return  regionCityVoList;
		}
		regionCityVoList =  Convert.toRegionCityVoList(regionCityDtoList);
		return  regionCityVoList;
	}

	private  List<Integer> getRegionIdList(Map<String, Object> selectParams){
        String type = ObjectCastUtil.castString(selectParams.get("type"));
        Integer dealerId = ObjectCastUtil.castInteger(selectParams.get("dealerId"));

        if(StringUtils.isBlank(type)){
        	return null;
		}

		List<Integer> regionIdList = new ArrayList<>();
        if("dealer".equals(type)){
			regionIdList = dealerService.getRegionId();
        }else if("store".equals(type)){
			regionIdList = storeService.getRegionId(dealerId);
        }
        if(null == regionIdList || regionIdList.size() < 1){
			regionIdList.add(0);
		}
		return regionIdList;
    }

	@Override
	public Paged<SubcompanyVo> getSubcompanyListPage(Map<String, Object> selectParams) {
		logger.info("分子公司列表入参 >>" + JSON.toJSONString(selectParams));
		Paged<SubcompanyVo> subcompanyVoList = new  Paged<SubcompanyVo>();
		Paged<SubcompanyDto> dto = subcompanyService.getSubcompanyListPage(ObjectCastUtil.castString(selectParams.get("name")),ObjectCastUtil.castString(selectParams.get("responsibleAccountName")),
						ObjectCastUtil.castInteger(selectParams.get("regionId")),
						ObjectCastUtil.castInteger(selectParams.get("pageNum"))==null ? 1 : ObjectCastUtil.castInteger(selectParams.get("pageNum")),
						ObjectCastUtil.castInteger(selectParams.get("pageSize"))==null ? 10 : ObjectCastUtil.castInteger(selectParams.get("pageSize")));
		List<SubcompanyDto> subcompanyDtoList  =  dto.getList();
		subcompanyVoList = Convert.toPagedSubcompanyVo(dto);
		if(subcompanyVoList.getList() !=null && subcompanyVoList.getList().size()>0){
			for (int i = 0; i < subcompanyVoList.getList().size(); i++) {
				//根据区域id 查询省市
				RegionInfoDto regionInfoDto = regionService.getCityNameByCityId(subcompanyVoList.getList().get(i).getRegionId());
				if(regionInfoDto != null ){
					subcompanyVoList.getList().get(i).setProvinceName(regionInfoDto.getProvinceName()==null ? null :regionInfoDto.getProvinceFullName() );
					subcompanyVoList.getList().get(i).setProvinceId(regionInfoDto.getProvinceId()==null ? null :regionInfoDto.getProvinceId() );
					subcompanyVoList.getList().get(i).setCityName(regionInfoDto.getCityName()==null ? null : regionInfoDto.getCityFullName());
					subcompanyVoList.getList().get(i).setCityId(regionInfoDto.getCityId()==null ? null : regionInfoDto.getCityId());
				}
			}
		}else{
			return  subcompanyVoList;
		}
		logger.info("分子公司列表出参 >>" + JSON.toJSONString(subcompanyVoList));
		return subcompanyVoList;
	}

	@Override
	public SubcompanyVo getSubcompany(Integer id) {
		logger.info("分子公司详情入参 >>" + JSON.toJSONString(id));
		SubcompanyVo subcompanyVo = new SubcompanyVo();
		SubcompanyDto subcompanyDto  = subcompanyService.getSubcompanyNameById(id);
		if(subcompanyDto ==null ){
			return  subcompanyVo;
		}
		RegionInfoDto regionInfoDto = regionService.getCityNameByCityId(subcompanyDto.getRegionId());
		subcompanyVo= Convert.toSubcompanyVo(subcompanyDto);
		subcompanyVo.setProvinceName(regionInfoDto.getProvinceName());
		subcompanyVo.setCityName(regionInfoDto.getCityName());
		subcompanyVo.setCityId(regionInfoDto.getCityId());
		subcompanyVo.setProvinceId(regionInfoDto.getProvinceId());
		subcompanyVo.setAddress(regionInfoDto.getProvinceFullName()+regionInfoDto.getCityFullName()+subcompanyVo.getAddress());
		return  subcompanyVo;
	}

	@Override
	public Boolean createSubcompany(SubcompanyVo subcompanyVo) {
		List<SubcompanyDto> byName = subcompanyService.getSubcompanyByName(subcompanyVo.getName());
		if (byName != null && byName.size() > 0) {
			throw new BizException(ResponseCodeEnum.OPTION_ERROR.getCode(), "名称重复，请重新输入");
		}
		SubcompanyDto byFullName = subcompanyService.getSubcompanyByFullName(subcompanyVo.getFullName());
		if (byFullName != null) {
			throw new BizException(ResponseCodeEnum.OPTION_ERROR.getCode(), "全称重复，请重新输入");
		}

		int num  =   subcompanyService.createSubcompany(Convert.toSubcompanyCreateDto(subcompanyVo));
		if (num>0){
			return true;
		}else{
			return false;
		}
	}


	@Override
	public Boolean modifySubcompany(SubcompanyVo subcompanyVo) {
		List<SubcompanyDto> byName = subcompanyService.getSubcompanyByName(subcompanyVo.getName());
		if (byName != null && byName.size() > 0 && byName.get(0).getId() != subcompanyVo.getId()) {
			throw new BizException(ResponseCodeEnum.OPTION_ERROR.getCode(), "名称重复，请重新输入");
		}
		SubcompanyDto byFullName = subcompanyService.getSubcompanyByFullName(subcompanyVo.getFullName());
		if (byFullName != null && byFullName.getId() != subcompanyVo.getId()) {
			throw new BizException(ResponseCodeEnum.OPTION_ERROR.getCode(), "全称重复，请重新输入");
		}

		int num  =   subcompanyService.modifySubcompany(Convert.toSubcompanyModifyDto(subcompanyVo));
		if (num>0){
			return true;
		}else{
			return false;
		}
	}

	@Override
	public Paged<OwnershipVo> getOwnershipListPage(Map<String, Object> selectParams) {
		logger.info("产权方列表入参 >>" + JSON.toJSONString(selectParams));
		Paged<OwnershipVo> ownershipVoList = new  Paged<OwnershipVo>();
		OwnershipVo ownershipVo;
		Paged<OwnershipDto> dto = ownershipService.getOwnershipListPage(ObjectCastUtil.castInteger(selectParams.get("pageSize"))==null ? 10 : ObjectCastUtil.castInteger(selectParams.get("pageSize")),
						ObjectCastUtil.castInteger(selectParams.get("pageNum"))==null ? 1 : ObjectCastUtil.castInteger(selectParams.get("pageNum")));
		List<OwnershipDto> ownershipDtoList  =  dto.getList();
		ownershipVoList = Convert.toPagedOwnershipVo(dto);
		if(ownershipVoList.getList()!=null && ownershipVoList.getList().size()>0){
			for (int i = 0; i < ownershipVoList.getList().size(); i++) {
				//根据区域id 查询省市
				RegionInfoDto regionInfoDto = regionService.getCityNameByCityId(ownershipVoList.getList().get(i).getRegionId());
				if(regionInfoDto != null ){
					ownershipVoList.getList().get(i).setProvinceName(regionInfoDto.getProvinceName()==null ? null :regionInfoDto.getProvinceFullName());
					ownershipVoList.getList().get(i).setProvinceId(regionInfoDto.getProvinceId()==null ? null :regionInfoDto.getProvinceId());
					ownershipVoList.getList().get(i).setCityName(regionInfoDto.getCityName()==null ? null : regionInfoDto.getCityFullName());
					ownershipVoList.getList().get(i).setCityId(regionInfoDto.getCityId()==null ? null : regionInfoDto.getCityId());
				}
			}
		}else{
			return  ownershipVoList;
		}
		logger.info("产权方列表出参 >>" + JSON.toJSONString(ownershipVoList));
		return ownershipVoList;
	}

	@Override
	public Boolean createOwnership(OwnershipVo ownershipVo) {
		OwnershipDto ownership = ownershipService.getOwnershipByName(ownershipVo.getName());
		if (ownership != null) {
			throw new BizException(ResponseCodeEnum.OPTION_ERROR.getCode(), "产权方已经存在");
		}
		if (ValidateUtil.isNumber(ownershipVo.getResponsiblePhone()) == false) {
			throw new BizException(ResponseCodeEnum.OPTION_ERROR.getCode(), "负责人电话必须为数字组成");
		}
		int num  =   ownershipService.createOwnership(Convert.toOwnershipCreateDto(ownershipVo));
		if (num>0){
			return true;
		}else{
			return false;
		}
	}

	@Override
	public Boolean modifyOwnership(OwnershipVo ownershipVo) {
		OwnershipDto ownership = ownershipService.getOwnershipByName(ownershipVo.getName());
		if (ownership != null && ownershipVo.getId() != ownership.getId()) {
			throw new BizException(ResponseCodeEnum.OPTION_ERROR.getCode(), "产权方已经存在");
		}
		if (ValidateUtil.isNumber(ownershipVo.getResponsiblePhone()) == false) {
			throw new BizException(ResponseCodeEnum.OPTION_ERROR.getCode(), "负责人电话必须为数字组成");
		}
		int num  =   ownershipService.modifyOwnership(Convert.toOwnershipModifyDto(ownershipVo));
		if (num>0){
			return true;
		}else{
			return false;
		}
	}

	@Override
	public OwnershipDetailVo getOwnershipById(Integer ownershipId) {
		OwnershipDetailVo ownershipDetailVo = new OwnershipDetailVo();
		OwnershipDto ownershipDto  = ownershipService.getOwnershipById(ownershipId);
		if(null == ownershipDto) {
			return null;
		}
		BeanUtils.copyProperties(ownershipDto, ownershipDetailVo);
		RegionInfoDto regionInfoDto = regionService.getCityNameByCityId(ownershipDto.getRegionId());
		if(regionInfoDto != null ){
			ownershipDetailVo.setProvinceId(regionInfoDto.getProvinceId());
			ownershipDetailVo.setCityId(regionInfoDto.getCityId());
		}
		return ownershipDetailVo;
	}

	@Override
	public List<SubcompanyVo> getOwnershipByProvinceId(Integer provinceId) {
		return Convert.toSubcompanyVoVoList(subCompanyBizService.getSubcompanyByCityId(provinceId));
	}

	@Override
	public List<RegionSubcompanyVo> getProvinceSubCompany() {
		return Convert.toRegionSubcompanyVo(regionBizService.getProvinceSubCompany());
	}
	
	@Override
	public Paged<MessageVo> getMessageListPage(Map<String, Object> map) {
		RiskEmailTypeEnum[] enums = RiskEmailTypeEnum.values();
		Integer pageSize = ObjectCastUtil.castInteger(map.get("pageSize"));
		Integer pageNum = ObjectCastUtil.castInteger(map.get("pageNum"));
		List<MessageVo> list =new ArrayList<>();
		for (RiskEmailTypeEnum emailEnum: enums) {
			MessageVo vo = new MessageVo();
			vo.setId(emailEnum.getValue());
			vo.setMessageType(emailEnum.getName());
			vo.setRuleDescription(RiskEmailTypeExplainEnum.getName(emailEnum.getValue()));
			list.add(vo);
		}
		
		List<MessageVo> collect = list.stream()
		.skip(pageSize * (pageNum - 1))
		.limit(pageSize).collect(Collectors.toList());
		Paged<MessageVo> page=new Paged<>(collect,list.size(),pageSize);
		return page;
	}
	
	@Override
	public List<RiskEmailVo> getlistRiskEmail(Integer type, Integer receiveType) {
		List<RiskEmailDto> list = riskEmailService.getByType(type, receiveType);
		if(null == list || list.isEmpty()) {
			return null;
		}
		List<RiskEmailVo> voList= new  ArrayList<>();
		for (RiskEmailDto dto : list) {
			RiskEmailVo vo = new RiskEmailVo();
			BeanUtils.copyProperties(dto, vo);
			voList.add(vo);
		}
		return voList;
	}
	
	@Override
	public Boolean modifyRiskEmail(List<RiskEmailModifyVo> list) {
		if(null == list || list.isEmpty()) {
			return true;
		}
		List<RiskEmailModifyDto> listDto = new  ArrayList<>(list.size());
		for (RiskEmailModifyVo vo : list) {
			RiskEmailModifyDto modifyDto = new RiskEmailModifyDto();
			BeanUtils.copyProperties(vo, modifyDto);
			listDto.add(modifyDto);
		}
		return riskEmailService.modify(listDto);
	}
}
